import axios from 'axios'
import { getToken } from './token'
import qs from 'qs'
import Vue from 'vue';
import { Toast } from 'vant';
import router from '../router'

Vue.use(Toast);
let instance = axios.create({
    baseURL: process.env.VUE_APP_BASE_URL,
    timeout: 10000,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
    }
})
// 添加请求拦截器
instance.interceptors.request.use(config=>{
    let token = getToken()
    if(config.method == 'post') {
        config.data = qs.stringify(config.data)
    }
    if(token) {
        config.headers['token'] = token
    }
    return config
})

function handleExpire() {
    Toast.fail('登录超时，请重新登录')
    setTimeout(() => {
        router.push({path: '/login'})
    }, 1500)
}
instance.interceptors.response.use(response=>{
    if (response.status == 200) {
        let code = response.data.code
        if(code == 200) {
            return Promise.resolve(response) 
        }else if(code == 400) {
            handleExpire()
            return Promise.reject(response.data.data)
        }else if(code == 404) {
            // Toast.fail(response.data.msg)
            return Promise.reject(response.data.msg)
        }else if(code == 401) {
            Toast.fail(response.data.msg)
            return Promise.reject(response.data.msg)
        }
    } else {
        Toast.fail(response.data.msg)
        return Promise.reject(response.data.msg)
    }
})


export function get(url, param) {
    return new Promise((resolve, reject) => {
        instance.get(url, param).then(res=>{
            resolve(res.data)
        }).catch(err=>{
            reject(err)
        })
    })
}

export function post(url, param) {
    return new Promise((resolve, reject) => {
        instance.post(url, param)
        .then(res=>{
            console.log('res', res)
            resolve(res)
        }).catch(err=>{
            reject(err)
        })
    })
}
